<template>
  <div style="margin: 20px 20px">

    <el-input
      style="width: 300px; margin-bottom: 20px;"
      placeholder="输入关键字进行过滤"
      v-model="filterText">
    </el-input>

    <el-tree
      :data="data"
      show-checkbox
      default-expand-all
      node-key="id"
      ref="tree"
      :filter-node-method="filterNode"
      highlight-current
      :props="defaultProps">
    </el-tree>

    <div class="buttons">
      <el-button :disabled="saveBtnDisabled" type="primary" @click="setSysAuthority">保存</el-button>
      <el-button @click="resetChecked">清空</el-button>
    </div>

  </div>
</template>
<script>
import menu from '@/api/acl/menu'

export default {
  data() {
    return {
      filterText: '',
      saveBtnDisabled: false,
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      roleId: ''

    };
  },

  watch: {
    $route(to, from) {
      this.init()
    },
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },

  created() {
    this.init()
  },

  methods: {
    init() {
      if (this.$route.params && this.$route.params.id) {
        this.roleId = this.$route.params.id
        this.findAuthoritiesByRoleId(this.roleId)
      }
    },

    findAuthoritiesByRoleId(roleId) {
      menu.findAuthoritiesByRoleId(roleId).then(response => {
        if (response.code === 200) {
          this.data = response.data.items
          const checked = response.data.checked
          this.setCheckedKeys(checked)
        }
      })
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    setSysAuthority() {
      const ids = this.$refs.tree.getCheckedKeys().join(",");
      menu.setSysAuthority(this.roleId, ids).then(response => {
        if(response.code === 200){
          this.$message({
            type:'success',
            message:'保存成功'
          })
          this.$router.push({ path: '/acl/role/list' })
        }
      })
    },

    setCheckedKeys(list) {
      this.$refs.tree.setCheckedKeys(list);
    },
    resetChecked() {
      this.$refs.tree.setCheckedKeys([]);
    }

  }
};
</script>
